package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.dao.jdbc.SettingDetailsJdbc;
import com.wuseguang.springcloud.service.SettingDetailsService;
import com.wuseguang.springcloud.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SettingDetailsServiceImpl implements SettingDetailsService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SettingDetailsJdbc detailsJdbc;

    @Autowired
    private ClassCardFieldService classCardFieldService;

    @Autowired
    private ClassCardService classCardService;

    /**
     * @描述 查询设置页面详情
     * @创建人 zm
     * @创建时间 2020/2/23
     */
    @Override
    public Map<String, Object> querySettingDetails(String deviceid) {
        Map<String, Object> stringObjectMap = detailsJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        return stringObjectMap;
    }

    /**
     * @描述 查询设备类型
     * @创建人 zm
     * @创建时间 2020/2/23
     */
    @Override
    public Map<String, Object> queryEquipmentType(String deviceid) {
        Map<String, Object> stringObjectMap = detailsJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("deviceType", stringObjectMap.get("deviceType"));
        classCardFieldService.deviceidAndCards(deviceid, "devicetypeflag", "0");
        return map;
    }

    /**
     * @描述 修改设备类型
     * @创建人 zm
     * @创建时间 2020/2/23
     */
    @Override
    public int updateEquipmentType(String deviceid, String deviceType) {
        String sql="  UPDATE bancard SET  classflag=1, dutyflag=1, picturesflag=1, videoflag=1, noticeflag=1, timetableflag=1 WHERE deviceid=?";
        detailsJdbc.updateByParameter(sql, deviceid);
        sql = "UPDATE bancard SET deviceType=? WHERE deviceid=?";
        return detailsJdbc.updateByParameter(sql, deviceType, deviceid);
    }

    /**
     * @描述 修改版本号
     * @创建人 zm
     * @创建时间 2020/4/6
     */
    @Override
    public int updateVersionNumber(String deviceid, String version) {
        //班牌
        Integer type = 0;
        if (version.contains("s")) {
            //校牌
            type = 1;
        }
        String sql = "UPDATE bancard SET version=? ,type = ?, classflag=1, dutyflag=1, picturesflag=1, videoflag=1, noticeflag=1, timetableflag=1 WHERE deviceid=?";
        return detailsJdbc.updateByParameter(sql, version, type, deviceid);
    }

    /**
     * @描述 添加截图
     * @创建人 zm
     * @创建时间 2020/2/27
     */
    @Override
    public int updateScreenShot(String deviceid, String ScreenShotUrl) {
        String sql = "UPDATE bancard SET screenshot=?,screentime=now() WHERE deviceid=?";
        classCardFieldService.deviceidAndCards(deviceid, "screenflag", "0");
        return detailsJdbc.updateByParameter(sql, ScreenShotUrl, deviceid);
    }

    /**
     * @描述 查询设备音量
     * @创建人 zm
     * @创建时间 2020/2/27
     */
    @Override
    public Map<String, Object> queryVolume(String deviceid) {
        String sql = "SELECT volume  FROM bancard WHERE deviceid=? LIMIT 1";
        Map<String, Object> map = null;
        try {
            map = detailsJdbc.queryMap(sql, deviceid);
        } catch (Exception e) {
            logger.info("queryVolume-->erorr={}", e);
        }
        classCardFieldService.deviceidAndCards(deviceid, "volumeflag", "0");
        return map;
    }

    @Override
    public Map<String, Object> queryUpGradeUrl(String deviceid) {
        String sql = "SELECT upgradeurl FROM bancard WHERE deviceid=? LIMIT 1";
        Map<String, Object> map = null;
        try {
            map = detailsJdbc.queryMap(sql, deviceid);
        } catch (Exception e) {
            logger.info("queryVolume-->erorr={}", e);
        }
        classCardFieldService.deviceidAndCards(deviceid, "upgradeflag", "0");
        return map;
    }

    /**
     * @描述 查询推送日志
     * @创建人 zm
     * @创建时间 2020/5/5
     */
    @Override
    public Result queryPushLog(String deviceid) {
        if (!StringUtils.isEmpty(deviceid)) {
            String sql = "SELECT id,deviceid,clientid,content,result,`time` FROM pushlog WHERE deviceid=? AND TO_DAYS(`time`) = TO_DAYS(NOW()) order by time desc ";
            return new Result(detailsJdbc.queryListMap(sql, deviceid));
        }
        String sql = "SELECT id,deviceid,clientid,content,result,`time` FROM pushlog WHERE TO_DAYS(`time`) = TO_DAYS(NOW()) order by time desc";
        return new Result(detailsJdbc.queryListMap(sql));
    }

    /**
     * @描述 查询班牌日志
     * @创建人 zm
     * @创建时间 2020/6/12
     */
    @Override
    public Result queryBancardLog(String deviceid, String time, Integer indexNo, Integer rows) {
        String sql = "SELECT  `deviceid`, `url`,`param`, `result`, `time`, `opertime` FROM bancardlog WHERE deviceid=? AND TO_DAYS(opertime)=TO_DAYS(?) ORDER BY id DESC ";

        List<Map<String, Object>> list = detailsJdbc.queryListMap(sql, deviceid, time);

        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);
        //返回数据
        return new Result(new PaginationUtil<>(list.size(), rows, tool.getList(), indexNo));
    }

    /**
     * @描述 修改班牌心跳日志是否开启 0关闭 1开启
     * @创建人 zm
     * @创建时间 2020/6/13
     */
    @Override
    public Result updateBancardLog(String deviceid, Integer type) {
        String sql = " UPDATE bancard  SET bancardlog=? WHERE deviceid=?";
        detailsJdbc.updateByParameter(sql, type, deviceid);
        //返回数据
        return new Result();
    }

    @Override
    public Result queryStudentInformation(String phone, String card, String name) {

        String s = "";

        if (!StringUtils.isEmpty(phone)) {
            s += " and t.phone=" + phone;
        }

        if (!StringUtils.isEmpty(card)) {
            s += " and t.card_number=" + card;
        }

        if (!StringUtils.isEmpty(name)) {
            s += " and t.student_name like '%" + name + "%'";
        }
        if (StringUtils.isEmpty(s)) {
            return new Result();
        }
        String sql = " SELECT t.student_name,t.phone,t.card_number,s.school_name,c.name  FROM student t LEFT JOIN school s ON(t.school_id=s.id) " +
                " LEFT JOIN   classes c ON(t.class_id=c.id) where 1=1 and t.state=0 " + s;

        //返回数据
        return new Result(detailsJdbc.queryListMap(sql));
    }


    /**
     * @描述 查询班牌心跳日志状态
     * @创建人 zm
     * @创建时间 2020/6/13
     */
    @Override
    public Result queryLogState(String deviceid) {
        String sql = " select  bancardlog type from bancard  WHERE deviceid=?";
        //返回数据
        return new Result(detailsJdbc.queryMap(sql, deviceid));
    }

    /**
     * @描述 根据设备号查所有心跳字段
     * @创建人 zm
     * @创建时间 2020/3/15
     */
    @Override
    public Map<String, Object> queryHeartBydeviceId(String deviceid) {
        String sql="  UPDATE bancard SET  classflag=1, dutyflag=1, picturesflag=1, videoflag=1, noticeflag=1, timetableflag=1 WHERE deviceid=?";
        detailsJdbc.updateByParameter(sql, deviceid);
        sql = "SELECT GROUP_CONCAT(name) as string FROM heartbeatfield";
        String s = detailsJdbc.queryString(sql);
        sql = "SELECT " + s + " FROM bancard WHERE deviceid=? LIMIT 1";
        Map<String, Object> map = null;
        try {
            map = detailsJdbc.queryMap(sql, deviceid);
            map.remove("deviceid");
        } catch (Exception e) {
            logger.info("queryVolume-->erorr={}", e);
        }
        return map;
    }

    @Override
    public Result queryManageClassList(String deviceid) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("type", 0);//横屏
        map.put("url", "https://oss.yuguozhijia.online/classroomteaching/hengping.png");
        list.add(map);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("type", 1);//竖屏
        map1.put("url", "https://oss.yuguozhijia.online/classroomteaching/suping.png");
        list.add(map1);
        return new Result(list);
    }

    /**
     * @描述 校验班牌密码
     * @创建人 zm
     * @创建时间 2020/4/3
     */
    @Override
    public Result landingOfClassCards(String deviceid, String password) {
        Map<String, Object> stringObjectMap = detailsJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return new Result(CodeUtil.DEVICE_AFTER_OPERATION);
        }
        String sql = "SELECT password  string FROM school WHERE id=?";
        String s = detailsJdbc.queryString(sql, stringObjectMap.get("school_id"));
        logger.info("landingOfClassCards==>,s={},password={}", s, password);
        if (StringUtils.isEmpty(s) || !MyDES.decryptBasedDes(s).equals(password)) {
            logger.info("password error");
            return new Result(CodeUtil.PASSWORD_ERROR);
        }
        return new Result();
    }

    @Override
    public Result upload(String deviceid, MultipartFile file, int type) {
        Map<String, Object> stringObjectMap = detailsJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return new Result(CodeUtil.DEVICE_AFTER_OPERATION);
        }

        logger.info("班牌 上传文件/图片/人脸/班牌日志");

        //文件url
        String url = CallbackSample.saveFile(file, stringObjectMap.get("school_id").toString(), type);
        logger.info("url:" + url);
        //判断文件是否上传失败
        if ("error".equals(url)) {
            return new Result(CodeUtil.UPLOAD_FAILURE);
        }
        return new Result((Object) url);
    }

    @Override
    public Result updateBanCardUploadLog(String deviceid) {
        String sql = "update bancard set logflag=1 where  deviceid=?";
        int i = detailsJdbc.updateByParameter(sql, deviceid);
        if (i > 0) {
            classCardService.deviceidAndCards(deviceid);
        }
        return new Result();
    }

    @Override
    public Result addBanCardUploadLog(String deviceid, String url) {
        String sql = "update bancard set logurl=?,logflag=0,logtime=now() where  deviceid=?";
        detailsJdbc.updateByParameter(sql, url, deviceid);
        return new Result();
    }

    @Override
    public Result queryBanCardUploadLog(String deviceid) {
        String sql = " SELECT deviceid,logurl,logtime FROM  bancard  WHERE  deviceid=? limit 1";
        return new Result(detailsJdbc.queryMap(sql, deviceid));
    }
}
